package com.yuyue.springFramework.note08.entity;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.lang.Nullable;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义智能实例化后处理器实现类，指定使用自定义注解@MyAutowried的构造器
 */
public class MySmartInstantiationAwareBeanPostProcessor
        implements SmartInstantiationAwareBeanPostProcessor {
    @Nullable
    @Override
    //重新指定构造器方法
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
            throws BeansException {
        //获取定义的构造器
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        if(declaredConstructors != null){
            List<Constructor<?>> collect = Arrays.stream(declaredConstructors).//获取数组流
                    filter(constructor -> //lambda表达式，筛选指定注解
                            constructor.isAnnotationPresent(MyAutowried.class))
                    .collect(Collectors.toList());

            Constructor[] constructors = collect.toArray(new Constructor[collect.size()]);

            if(constructors.length != 0) {
                System.out.println("指定@MyAutowried注解的构造器");
            }

            return constructors.length != 0 ? constructors : null;
        }
        return null;
    }
}
